<?php
require_once '../libs/common.php';
setCosHeader();
$database=getDbConn();
$action=$_GET['action'];
if($action=="list"){
	$page=1;
	if(isset($_GET['page'])){
		$page=$_GET['page'];
	}
	$startnum= ($page-1)*9;//开始条数    
	$sql = 'select * from shop limit '.$startnum.',9';
	$result = $database->queryAll($sql);
	echo json_encode($result);
}else if($action=="detail"){
	$sql = 'select * from shop where id = :id';
	$array = array(
	      ':id' =>$_GET['id']
	);
	$result = $database->queryOne($sql, $array);
	echo json_encode($result);
}else if($action=="category_by_parent"){
	$shop_category_sql="select * from shop_category where parentid= :parentid order by sort asc";
	$data = array(
		':parentid' => $_GET['parentid']
	);
	$shopcategorys = $database->queryAll($shop_category_sql,$data);
	foreach ($shopcategorys as $key => $vo) {
		$shopcategorys[$key]['checked']=false;
		if($vo['level']==0){
			$shopcategorys[$key]['count']=getShopCount_level0($vo['id']);
		}else if($vo['level']==1){
			$shopcategorys[$key]['count']=getShopCount_level1($vo['id']);
		}else{
			$shopcategorys[$key]['count']=getShopCount_level2($vo['id']);
		}
	}
	echo json_encode($shopcategorys);
}else if($action=="attr"){
	$sql="select * from attr";
	$result=$database->queryAll($sql);
	echo json_encode($result);
}
function getShopCount_level0($cid){
	global $database;
	$shop_category_sql="select id from shop_category where parentid= :parentid order by sort asc";
	$data = array(
		':parentid' => $cid
	);
	$level1 = $database->queryAll($shop_category_sql,$data);
	$inarr=array();
	foreach ($level1 as $key => $value) {
		$data = array(
			':parentid' => $value['id']
		);
		$level2 = $database->queryAll($shop_category_sql,$data);
		foreach ($level2 as $key1 => $value1) {
			$inarr[]=$value1['id'];
		}
	}
	$instr=implode(',',$inarr);
	$sql = 'select count(*) from shop where cid in('.$instr.')';
	$count = $database->queryOne($sql);
	if($count){
		return $count['count(*)'];
	}else{
		return 0;
	}
}
function getShopCount_level1($cid){
	global $database;
	$shop_category_sql="select id from shop_category where parentid= :parentid order by sort asc";
	$data = array(
		':parentid' => $cid
	);
	$inarr=array();
	$level2 = $database->queryAll($shop_category_sql,$data);
	foreach ($level2 as $key1 => $value1) {
		$inarr[]=$value1['id'];
	}
	$instr=implode(',',$inarr);
	$sql = 'select count(*) from shop where cid in('.$instr.')';
	$count = $database->queryOne($sql);
	if($count){
		return $count['count(*)'];
	}else{
		return 0;
	}
}
function getShopCount_level2($cid){
	global $database;
	$sql = 'select count(*) from shop where cid='.$cid;
	$data = array(
		':cid' => $cid
	);
	$count = $database->queryOne($sql);
	if($count){
		return $count['count(*)'];
	}else{
		return 0;
	}
	
}